package online.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import online.entity.UserDao;
import online.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: 狼芒
 * @Date: 2021/10/3 16:50
 * @Descrintion:
 * @version: 1.0
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    LoginService loginService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.error("UserRealm --> 授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //取出认证中传输的值,获取到User
        UserDao user = (UserDao) subject.getPrincipal();
        if (user.getAccount().equals("456")) {
            simpleAuthorizationInfo.addStringPermission("shiro:role");
        }
        simpleAuthorizationInfo.addStringPermission("user:add");
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.error("UserRealm --> 认证");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        //获取用户名
        String username = usernamePasswordToken.getUsername();
        if (username == null) {
            return null;
        }
        UserDao user = loginService.getOne(new QueryWrapper<UserDao>().eq("account", username));
        if (user == null) {
            return null;
        }
        //密码认证，shiro去做
        return new SimpleAuthenticationInfo(user, user.getPassword(), username);
    }
}
